#!/usr/bin/env python
from sys import exit
from os import environ, sep
from random import *
from math import sin, cos

try:
	import pygame
	from pygame.locals import *
	
except ImportError:
	print "Falta o pacote pygame para executar o jogo."
	exit()
	
class Snake(pygame.sprite.Sprite):
	def __init__(self, x_mapa, y_mapa):
		self.x_mapa , self.y_mapa = x_mapa, y_mapa
		self.image = self.image = pygame.image.load("fish_D1.png").convert_alpha()

		self.pos = [0, 0]
		self.directions = []
		self.body = []
		self.length = 3
		self.angle = 180
		self.alive = True
		self.frame = 0

	def update(self):
		"""
		Executado a cada loop do jogo, atualiza a snake.
		"""
		
		#Insere a nova posicao da head snake
		self.body.insert(0, list(self.pos))

		#Regular o tamanho do corpo 
		self.body = self.body[0:self.length]

		self.frame += 1
		if self.frame == 10: self.frame = 0

		#Mover 16 pixels de acordo com o angulo
		peixe = choice([1, 2, 3])
		if self.angle == 0:
			self.pos[1] -= 32
			self.image = pygame.transform.flip(pygame.image.load("fish%d_D%d.png"%(peixe, 1)).convert_alpha(), 0, 1)
			#print "U"
		if self.angle == 90:
			self.pos[0] -= 32
			self.image = pygame.transform.flip(pygame.image.load("fish%d_R%d.png"%(peixe, 1)).convert_alpha(), 1, 0)
			#print "L"
		if self.angle == 180:
			self.pos[1] += 32
			self.image = pygame.image.load("fish%d_D%d.png"%(peixe, 1)).convert_alpha()
			#print "D"
		if self.angle == 270:
			self.pos[0] += 32
			self.image = pygame.image.load("fish%d_R%d.png"%(peixe, 1)).convert_alpha()
			#print "R"

		self.directions.insert(0, self.image)			
		self.directions = self.directions[0:len(self.directions)]

		#Cross the sea
		if self.pos[0] >= self.x_mapa:
			self.pos[0] -= self.x_mapa
		elif self.pos[0] < 0:
			self.pos[0] += self.x_mapa
			
		if self.pos[1] >= self.y_mapa:
			self.pos[1] -= self.y_mapa
		elif self.pos[1] < 0:
			self.pos[1] += self.y_mapa

		#Se a cabeca se encontrar com o corpo, morre.
		for b in self.body[2:]:
			if self.pos == b:
				self.alive = False
				
class Fruit():
	def __init__(self, x_mapa, y_mapa):
		self.x_mapa, self.y_mapa = x_mapa, y_mapa
		self.change_pos()
		self.size = 20
		self.image = pygame.image.load("food.png").convert_alpha()

	def change_pos(self):
		"""
		Move a fruta para uma posicao randomica.
		"""
		self.pos = [randint(1, (self.x_mapa/32) - 1) * 32, randint(1, (self.y_mapa/32) - 1) * 32]
		self.size = 20

	def update(self):
		if self.size > 0:
			self.size -= 1
			
		self.image = pygame.transform.smoothscale(pygame.image.load("food.png").convert_alpha(), (20 + self.size, 20 + self.size))
		self.image = pygame.transform.flip(self.image, self.size % 2 == 0, self.size % 3 == 0)

def main():
	"""
	Funcao principal.
	"""
	
	#Coloca a posicao da janela do jogo no centro
	environ["SDL_VIDEO_CENTERED"] = "1"
	pygame.init()

	#Setar a janela
	LARGURA_DA_TELA = 640
	ALTURA_DA_TELA = 480
	screen = pygame.display.set_mode((LARGURA_DA_TELA, ALTURA_DA_TELA), HWSURFACE|DOUBLEBUF)
	pygame.display.set_caption("Snake")

	background = pygame.image.load("fundo.png").convert()
	#Instanciar os objetos

	snake = Snake(LARGURA_DA_TELA, ALTURA_DA_TELA)
	fruit = Fruit(LARGURA_DA_TELA, ALTURA_DA_TELA)
	font = pygame.font.SysFont("malige", 32)

	anim = 0.0
	xpixels = range(0, 640, 10)
	ypixels = range(0, 480, 10)
	pause = False
	pingo = 0
	while True:
		#Coletar os eventos
		for e in pygame.event.get():
			if e.type == QUIT:
				exit()
				
			if e.type == KEYDOWN:
				if e.key == K_ESCAPE:
					pygame.quit()
					return

				if e.key == K_UP:
					if snake.angle != 180:
						snake.angle = 0
				elif e.key == K_LEFT:
					if snake.angle != 270:
						snake.angle = 90
				elif e.key == K_DOWN:
					if snake.angle != 0:
						snake.angle = 180
				elif e.key == K_RIGHT:
					if snake.angle != 90:
						snake.angle = 270

				if e.key == K_p:
					pause = not pause
					if pause:
						text_pause = font.render("PAUSE", 1, (100, 100, 0))
						posicao_texto = (LARGURA_DA_TELA/2 - text_pause.get_width()/2, ALTURA_DA_TELA/2 - text_pause.get_height()/2)
						screen.blit(text_pause, posicao_texto)
						pygame.display.update()
						while True:
							event = pygame.event.wait()
							if event.type == KEYDOWN and event.key == K_p: 
								pygame.time.wait(300)
								break

		snake.update()
		fruit.update()

		if snake.pos == fruit.pos:
			fruit.change_pos()
			snake.length += 1
			pingo = anim

		#Blitar a animacao da tela
		
		anim += 0.1
		for x in xpixels:
			xpos = (x + (cos(anim + x * .01) * 10)) + 20
			for y in ypixels:
				ypos = (y + (sin(anim + y * .01) * 10)) + 20
				screen.blit(background, (x, y), (xpos, ypos, 15, 15), 0)
					
		#Blitar a snake
		for (corpo, direcao) in zip(snake.body, snake.directions):
			screen.blit(direcao, (corpo[0], corpo[1]), (0, 0, 32, 32))

		#Blitar os objetos
		if anim < pingo + 1:
			screen.blit(pygame.image.load("pingo.png").convert_alpha() , (fruit.pos[0] - 35, fruit.pos[1]- 35))
			
		if fruit.size == 0:
			screen.blit(pygame.image.load("sombra.png").convert_alpha() , (fruit.pos[0] - 10, fruit.pos[1]- 10))		
			screen.blit(fruit.image, (fruit.pos[0], fruit.pos[1]), (0, 0, 32, 32))		
		else:	
			screen.blit(fruit.image, (fruit.pos[0], fruit.pos[1]), (0, 0, 20 + fruit.size, 20 + fruit.size), 0)	
				
		ren = font.render("Score: %d" % (snake.length-3), 1, (255, 255, 255))
		screen.blit(ren, (5, 5))
		
		pygame.display.flip()

		if not snake.alive:
			gameovertext = font.render("You died!", 1, (100, 0, 0))
			posicao_texto = (LARGURA_DA_TELA/2 - gameovertext.get_width()/2, ALTURA_DA_TELA/2 - gameovertext.get_height()/2)
			screen.blit(gameovertext, posicao_texto)
			pygame.display.flip()
			pygame.time.wait(2000)
			snake = Snake(LARGURA_DA_TELA, ALTURA_DA_TELA)
			fruit = Fruit(LARGURA_DA_TELA, ALTURA_DA_TELA)

		pygame.time.Clock().tick(10)

if __name__ == "__main__":
	main()
